import axios, {AxiosRequestConfig} from "axios";
import {router} from '@/router/router';
// import {useRouter} from "vue-router";
import { ElMessage } from 'element-plus'

const request = axios.create({
    baseURL: "/api",
});

request.interceptors.request.use(
    function (config:AxiosRequestConfig) {

      if (localStorage.getItem('token'))  config.headers!.token = 'Bearer '+(localStorage.getItem('token') || '')
        return config;
    },
    function (err) {
        return Promise.reject(err);
    }
);

request.interceptors.response.use(
    function (res) {
        return res;
    },
    function (err) {

        if (err.response.data) {
            ElMessage({
                message:err.response.data.message,
                type:'error',
            })
            // console.log(err.response.status)
            if (err.response.status === 401) {
                router.push({path:'/login'})
            }
        }

        return Promise.reject(err);
    }
);

export default request;
